/* eslint-disable @typescript-eslint/no-unused-vars */
import { List, Modal, Checkbox, Icon, Button } from 'antd-mobile-v2';
import * as React from 'react';
import { Props, State } from '../type';
import './index.less';
import styles from './index.module.less';
import { GetDataByExternalUrl } from '../../common/services';
import noDataImg from '@/assets/images/no-data.png';

export class CheckboxSelect extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  constructor(props: Props) {
    super(props);
    this.state = {
      isModal: false,
      showModal: false,
      //选中并确认的值
      selectedValue: [],
      //选中值
      checkedList: [],
      options: []
    };
  }

  public componentDidMount() {
    if (!this.props.form) return;
    const values = this.props.form?.getFieldValue(this.props.code);
    if (values) {
      this.setState({
        selectedValue: values
      });
    }

    this.getExternalData();
  }

  private async getExternalData() {
    // 是否有设置外部url
    if (
      this.props.useExternal &&
      this.props.externalOption &&
      this.props.externalOption.url
    ) {
      const data = await GetDataByExternalUrl(this.props.externalOption, {});
      if (data) {
        // let options = data.map((el)=>{
        //   return {
        //     value:el.businessId,
        //     text:el.businessName,
        //   }
        // })
        this.setState({
          options: data
        });
      }
    }
  }

  private showModal = (e: any) => {
    const values = this.props.form?.getFieldValue(this.props.code);
    e.preventDefault();
    if (this.props.disabled) return;
    if (this.props.value) {
      return setTimeout(() => {
        this.setState({
          selectedValue: this.props.value
        });
        this.setState({
          showModal: true,
          checkedList: this.state.selectedValue ? [...this.state.selectedValue] : []
        });
      }, 0);
    }
    if (values) {
      return setTimeout(() => {
        this.setState({
          selectedValue: values
        });
        this.setState({
          showModal: true,
          checkedList: this.state.selectedValue ? [...this.state.selectedValue] : []
        });
      }, 0);
    }
    this.setState({
      showModal: true,
      checkedList: this.state.selectedValue ? [...this.state.selectedValue] : []
    });
  };
  onClose = () => {
    this.setState({
      showModal: false
    });
  };
  public closest(el: any, selector: any) {
    const matchesSelector =
      el.matches ||
      el.webkitMatchesSelector ||
      el.mozMatchesSelector ||
      el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }
  onWrapTouchStart = (e: any) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = this.closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  };
  handleChecked = (e: any, item: any) => {
    const checked = e.target.checked;
    const checkedList = this.state.checkedList
      ? [...this.state.checkedList]
      : [];
    if (checked) {
      checkedList.push(item);
    } else {
      const i = checkedList.findIndex((ik: any) => ik.value === item.value);
      checkedList.splice(i, 1);
    }
    this.setState({
      checkedList: checkedList
    });
  };
  confirm = () => {
    const selectedValue =
      this.state.checkedList &&
      this.state.checkedList.map((item: any) => {
        return {
          value: item.value,
          text: item.text || item.label,
          label: item.text || item.label
        };
      });
    console.log('selectedValue', selectedValue, this.state.checkedList);
    this.setState({
      showModal: false,
      selectedValue: this.state.checkedList ? [...this.state.checkedList] : []
    });
    this.props.form?.setFieldsValue({
      [this.props.code]: selectedValue
    });
    this.props.onChange && this.props.onChange(selectedValue);
  };
  cancel = () => {
    this.setState({
      showModal: false
    });
  };
  modal = (radioOptions: any, fieldProps: any) => {
    return (
      <Modal
        className='checkboxModal'
        visible={this.state.showModal || false}
        popup
        onClose={this.onClose}
        animationType='slide-up'
        wrapProps={{ onTouchStart: this.onWrapTouchStart }}
      >
        <List
          renderHeader={() => (
            <div className='modalTitle'>
              {this.props.name}
              <Icon type='cross' className='closeIcon' onClick={this.onClose} />
            </div>
          )}
          renderFooter={() =>
            radioOptions && radioOptions.length > 0 ? (
              <div className='modalFooter'>
                <Button className='modalButton' onClick={this.cancel}>
                  取消
                </Button>
                <Button
                  className='modalButton'
                  type='primary'
                  onClick={this.confirm}
                >
                  确定
                </Button>
              </div>
            ) : null
          }
        >
          <List.Item>
            {radioOptions && radioOptions.length > 0 ? (
              radioOptions.map((i: any) => (
                <Checkbox.CheckboxItem
                  key={i.value}
                  checked={
                    this.state.checkedList &&
                    this.state.checkedList.findIndex(
                      (item: any) => item.value === i.value
                    ) >= 0
                  }
                  onChange={(e: any) => {
                    // 先触发一次getFieldProps的onChange方法，标记当前表单已经被手动操作过，用于识别表单编辑后路由离开拦截
                    if (fieldProps?.onChange) fieldProps?.onChange(e);
                    this.handleChecked(e, i);
                  }}
                >
                  {i.label}
                </Checkbox.CheckboxItem>
              ))
            ) : (
              <div style={{ textAlign: 'center' }}>
                <img
                  src={noDataImg}
                  alt=''
                  style={{ width: '120px', height: '120px' }}
                />
                <span style={{ display: 'block' }}>
                  {this.props.notFoundContent}
                </span>
              </div>
            )}
          </List.Item>
        </List>
      </Modal>
    );
  };

  public render() {
    const { getFieldProps } = this.props.form || {};
    const {
      error,
      form,
      name,
      code,
      required,
      useExternal,
      options,
      placeholder,
      disabled,
      value,
      className,
      ...otherProps
    } = this.props;

    const whichOptions = useExternal ? this.state.options : options;
    whichOptions.forEach((item: any) => {
      item.label = item.text || item.label;
    });

    // 控件组通过 getFieldValue(code)获取，非控件组通过value
    const checkedValuesList = form?.getFieldValue(code) || value || [];
    let checkedValues = [];
    if (Array.isArray(checkedValuesList)) {
      checkedValues = checkedValuesList?.map(
        (item: any) => item.text || item.label
      );
    }
    // console.log("code-----{}", code, checkedValuesList);

    const extra = checkedValues?.length ? (
      checkedValues?.join(';')
    ) : (
      <span style={{ color: '#B8B8B8' }}>{placeholder}</span>
    );

    let fieldProps: any = {};

    if (getFieldProps) {
      fieldProps = {
        ...getFieldProps(this.props.code, {
          rules: [{ required: this.props.required, message: `请选择${name}` }]
        })
      };
    }

    return (
      <div className={styles.checkboxContainer}>
        <List.Item
          arrow='horizontal'
          onClick={this.showModal}
          extra={extra}
          {...otherProps}
          {...fieldProps}
          className={
            className + ' checkbox-select-wrap ' + disabled ? 'disabled' : ''
          }
        >
          {name}
        </List.Item>
        {this.modal(whichOptions, fieldProps)}
      </div>
    );
  }
}
